﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using blackhouse.WebNemo.Business.Groups;

namespace blackhouse.WebNemo.Web {
    public class NemoIdDynamicImageFriendlyModule : IHttpModule {

        public void Dispose() { }

        public void Init(HttpApplication context) {
            context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
        }

        void context_AuthorizeRequest(object sender, EventArgs e) {
            string url = HttpContext.Current.Request.RawUrl;
            if (url.Contains("nemo/") || url.Contains("nemoin/")) {
                this.Rewrite(url);
            }
        }

        private void Rewrite(string url) {


            Regex r = new Regex(@"(nemo|nemoin)/(.*)/(.*)/(\d*)/(\d*)x(\d*)-(.*)");
            Match m = r.Match(url);
            if (m.Success) {
                string newUrl = string.Format("/NemoIdDynamicImage.ashx?table={0}&column={1}&recordId={2}&width={3}&height={4}&file={5}&fillInner={6}", m.Groups[2].Value, m.Groups[3].Value, m.Groups[4].Value, m.Groups[5].Value, m.Groups[6].Value, m.Groups[7].Value, (m.Groups[1].Value == "nemo") ? "0" : "1");
                HttpContext.Current.RewritePath(newUrl);
            }
        }

    }
}